package com.lcf.app.shiro.common;

import com.alibaba.fastjson.JSON;
import com.lcf.app.shiro.common.model.User;
import com.lcf.app.shiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author ChenFei
 * @date 2021/11/2
 * <p>
 * shiroConfig 配置吧已经注入了，这里不用再加@Component注解,否则会抛出异常
 */
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 功能描述：验证权限的时候调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = String.valueOf(principalCollection.getPrimaryPrincipal());
        Set<String> roles = userService.getRoles();
        Set<String> perms = userService.getPerms();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);
        log.info("用户当前权限username:{},roles:{},perms:{}", username, JSON.toJSONString(roles), JSON.toJSONString(perms));
        return authorizationInfo;
    }

    /**
     * 功能描述：登录的时候调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //token转换为登录的时候定义的类型
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        char[] password = token.getPassword();
        if (username == null || password == null) {
            throw new MyException(100, "请求参数异常");
        }
        User user = userService.getByName(username);
        if (user == null) {
            throw new MyException(101, "用户名或密码异常");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        if (user.getSalt() != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        }
        return info;
    }

}
